package com.persion.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.persion.common.annotation.Anonymous;
import com.persion.common.config.RuoYiConfig;
import com.persion.common.constant.Constants;
import com.persion.common.core.domain.AjaxResult;
import com.persion.common.core.redis.RedisCache;
import com.persion.common.utils.DateUtils;
import com.persion.common.utils.StringUtils;
import com.persion.common.utils.bean.BeanUtils;
import com.persion.common.utils.file.FileUtils;
import com.persion.domain.Activity;
import com.persion.domain.FrontCategory;
import com.persion.domain.JoinAct;
import com.persion.dto.Params;
import com.persion.service.ActivityService;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.persion.service.JoinActService;
import com.persion.vo.ActivityVo;
import com.persion.vo.AddressVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 活动记录表(Activity)表控制层
 *
 * @author WangFK
 * @since 2024-01-26 13:43:31
 */
@RestController
@Slf4j
@RequestMapping("/manage/active")
public class ActivityController {
    /**
     * 服务对象
     */
    @Resource
    private ActivityService activityService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private JoinActService joinActService;
    /**
     * 截至今天还在举行的活动并 进行数据清洗
     * @Author WangFK
     * @Date 2024/1/26 16:16
     * @Param []
     * @return com.persion.common.core.domain.AjaxResult
     **/
    @GetMapping("/getOnLineActiveList")
    public AjaxResult getOnLineActiveList(){
        String today = DateUtil.today();
        String key="care-persion:getOnLineActiveList:"+today;
        Object value = redisCache.getCacheObject(key);
        if (ObjectUtil.isEmpty(value)){
            LambdaUpdateWrapper<Activity> lqw = new LambdaUpdateWrapper<Activity>()
                    .lt(Activity::getActEtime, today);
            // 下架所有过期活动
            activityService.update(lqw
                    .set(Activity::getActStatus,"1"));
            List<Integer> ActiviIds = activityService.list(lqw).stream().map(Activity::getActId).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(ActiviIds)){
                joinActService.update(
                        new LambdaUpdateWrapper<JoinAct>().in(JoinAct::getActId,ActiviIds).set(JoinAct::getOpStatus,"1"));
            }

            redisCache.setCacheObject(key,"value",30,TimeUnit.MINUTES);
        }
        LambdaQueryWrapper<Activity> lqw = new LambdaQueryWrapper<Activity>()
                .eq(Activity::getActStatus, "0")
                .gt(Activity::getActEtime, today);
        List<Activity> list = activityService.list(lqw);
        return AjaxResult.success(list);
    }

    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    @Anonymous
    @GetMapping("/list")
    public AjaxResult list(Params params) {
        Page<Activity> activityPage = new Page<>(params.pageNum, params.pageSize);
        LambdaQueryWrapper<Activity> lqw = new LambdaQueryWrapper<>();
        String search = params.getSearch();
        lqw.like(StringUtils.isNotEmpty(search), Activity::getActTitle, search).or()
                .like(StringUtils.isNotEmpty(search), Activity::getActCharge, search).or()
                .like(StringUtils.isNotEmpty(search), Activity::getActPlace, search)
                .eq(StringUtils.isNotEmpty(params.getCode()), Activity::getAreaCode, params.getCode())
                .like(StringUtils.isNotEmpty(params.getActEtime()), Activity::getActEtime, params.getActEtime())
                .like(StringUtils.isNotEmpty(params.getActBtime()), Activity::getActBtime, params.getActBtime())
                .eq(StringUtils.isNotEmpty(params.getActStatus()), Activity::getActStatus, params.getActStatus());
        if (ObjectUtil.isEmpty(params.getFlag())){
            lqw.eq(Activity::getActStatus, "0");
        }
        activityPage = activityService.page(activityPage, lqw);
        List<Activity> records = activityPage.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return AjaxResult.warn("暂无信息");
        }
        List<ActivityVo> activityVos = BeanUtil.copyToList(records, ActivityVo.class);
        activityVos.stream().forEach(item -> {
            item.setActPlaceDetail(item.getProvinceName() + item.getCityName() + item.getDistrictName() + item.getActPlace());
        });
        return AjaxResult.success()
                .put("rows", activityVos)
                .put("total", activityVos.size());
    }

    /**
     * 获取全国地址
     *
     * @return
     */
    @GetMapping("/getAddressAndCode")
    public List<AddressVo> getAddressAndCode() {

        String key = "care-persion:address:list";
        List<AddressVo> value = redisCache.getCacheList(key);
        if (ObjectUtil.isNotEmpty(value)) {
            return value;
        }
        String url = "https://www.mxnzp.com/api/address/list";
        HashMap<String, Object> params = new HashMap<>();
        params.put("app_id", "idgorwnnojpowkrl");
        params.put("app_secret", "wDKi9GfjUSlvAKb5ftYmV0IoB02PU5ys");

        AjaxResult result = JSONUtil.toBean(JSONUtil.toJsonStr(HttpUtil.get(url, params)), AjaxResult.class);
        List<Map> maps = JSONUtil.toList(result.get("data").toString(), Map.class);
        ArrayList<AddressVo> addresses = new ArrayList<>();
        maps.stream().forEach(item -> {
            AddressVo address = new AddressVo();
            ArrayList<AddressVo> addresses1 = new ArrayList<>();
            String code = item.get("code").toString();
            String name = item.get("name").toString();
            address.setCode(code);
            address.setName(name);
            List<Map> pchilds = Convert.toList(Map.class, item.get("pchilds"));
            pchilds.stream().forEach(item1 -> {
                AddressVo address1 = new AddressVo();
                ArrayList<AddressVo> addresses2 = new ArrayList<>();
                String code1 = item1.get("code").toString();
                String name1 = item1.get("name").toString();
                address1.setCode(code1);
                address1.setName(name1);
                List<Map> cchilds = Convert.toList(Map.class, item1.get("cchilds"));
                cchilds.stream().forEach(item2 -> {
                    AddressVo address2 = new AddressVo();
                    String code2 = item2.get("code").toString();
                    String name2 = item2.get("name").toString();
                    address2.setCode(code2);
                    address2.setName(name2);
                    addresses2.add(address2);
                });
                address1.setChildren(addresses2);
                addresses1.add(address1);
            });
            address.setChildren(addresses1);
            addresses.add(address);
        });
        redisCache.setCacheList(key, addresses);
        redisCache.expire(key, 12, TimeUnit.HOURS);
        return addresses;
    }

    /**
     * 上下架分类状态
     *
     * @param activity
     * @return
     */
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody Activity activity) {
        LambdaUpdateWrapper<Activity> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(Activity::getActId, activity.getActId())
                .set(Activity::getActStatus, activity.getActStatus());
        return activityService.update(lqw) ? AjaxResult.success() : AjaxResult.warn("修改状态失败");
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        return AjaxResult.success(activityService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param activity 实体对象
     * @return 新增结果
     */
    @PostMapping
    public AjaxResult insert(@RequestBody Activity activity) {
        Date actBtime = activity.getActBtime();
        Date actEtime = activity.getActEtime();
        if (DateUtil.compare(DateUtil.yesterday(), actBtime) > 0) {
            return AjaxResult.warn("不能早于今天：" + DateUtil.now());
        }
        if (DateUtil.compare(actBtime, actEtime) > 0) {
            return AjaxResult.warn("开始时间：" + DateUtil.format(actBtime, "yyyy-MM-dd") + "不能比结束时间：" + DateUtil.format(actEtime, "yyyy-MM-dd") + "晚");
        }
        if (StringUtils.isEmpty(activity.getActTitle()) || StringUtils.isEmpty(activity.getActIntro()) ||
                StringUtils.isEmpty(activity.getActPhoto()) || StringUtils.isEmpty(activity.getAreaCode()) ||
                StringUtils.isEmpty(activity.getActPlace()) || StringUtils.isEmpty(activity.getActCharge()) ||
                StringUtils.isEmpty(actBtime.toString()) || StringUtils.isEmpty(actEtime.toString())) {
            return AjaxResult.warn("请按规范填写!");
        }
        if (ObjectUtil.isNotEmpty(activity.getActId())) {
            return update(activity);
        }
        return AjaxResult.success(activityService.save(activity));
    }

    /**
     * 修改数据
     *
     * @param activity 实体对象
     * @return 修改结果
     */
    @PutMapping
    public AjaxResult update(@RequestBody Activity activity) {
        Activity byId = activityService.getById(activity.getActId());
        if (!activity.getActPhoto().equalsIgnoreCase(byId.getActPhoto())){
            // 本机地址
            String localPath = RuoYiConfig.getProfile();
            String downloadPath = localPath + StringUtils.substringAfter(byId.getActPhoto(), Constants.RESOURCE_PREFIX);
            FileUtils.deleteFile(downloadPath);
        }
        return AjaxResult.success(activityService.updateById(activity));
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public AjaxResult delete(@PathVariable Serializable id) {
        return AjaxResult.success(activityService.removeById(id));
    }
}

